#!/usr/bin/env node

import minimist, { ParsedArgs } from 'minimist';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { resolve } from 'path';
import { printError, printSuccess } from './print';
type DepType = 'scss' | 'scssmodule';

/**
 * 同步写入 JSON 文件（原生实现）
 * @param {string} filePath - 目标文件路径
 * @param {any} data - 要写入的 JavaScript 对象
 * @param {Object} [options] - 配置选项（同异步版本）
 * @returns {boolean} - 写入成功返回 true
 */
const writeJsonSync = function (filePath: string, data: any) {
    if (!existsSync(filePath)) {
        throw new Error(filePath + '目录不存在');
    }
    try {
        const jsonString = JSON.stringify(data, undefined, 2);
        // 4. 同步写入文件
        writeFileSync(filePath, jsonString, 'utf8');
        return true;
    } catch (err) {
        console.error('写入 JSON 文件时出错：', err);
        return false;
    }
    // 3. 转换为 JSON 字符串
};
export const updateDepList = function (depObj: Record<string, string>) {
    try {
        const pkg = getJson(resolve('./package.json'));
        pkg.devDependencies = { ...pkg.devDependencies, ...depObj };
        writeJsonSync(resolve('./package.json'), pkg);
        return true;
    } catch {
        return false;
    }
};
export const getJson = (path: string) => {
    try {
        return JSON.parse(readFileSync(path).toString());
    } catch {
        return {};
    }
};

const main = function () {
    const args: ParsedArgs = minimist(process.argv.slice(2));
    const type = args.type as DepType | undefined;
    const newType = type || 'scss';
    if (!newType || !['scss', 'scssmodule'].includes(newType)) {
        throw new Error('❌ 请指定正确的类型：--type scss 或 --type scssmodule');
    }
    const depObj: Record<string, string> = {
        'stylelint-config-recommended-scss': '^14.0.0',
        'stylelint-config-standard': '^36.0.0',
        'stylelint-order': '^6.0.4',
        'stylelint-prettier': '^5.0.0',
        'stylelint-scss': '^6.2.1',
    };
    const isOK = updateDepList(depObj);
    if (isOK) {
        printSuccess('更新依赖成功，执行pnpm i即可安装');
        return;
    }
    const depListString = Object.keys(depObj)
        .map((dep) => {
            return `${dep}@${depObj[dep].replace('^', '')}`;
        })
        .join(' ');
    printError('自动更新异常，请手动更新：\n' + `pnpm i -D ${depListString}`);
};

main();
